import 'dart:io';
import 'package:inmotion_pro/config/r.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

// 头像视图
class AvatarView extends StatelessWidget {
  // 路径
  final String avatarPath;
  // 是否登录
  final bool isLoggedIn;
  // 大小
  final double size;

  const AvatarView({
    super.key,
    required this.avatarPath,
    required this.isLoggedIn,
    required this.size,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: size,
      height: size,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(18.w),
        child: isLoggedIn
            ? (avatarPath.isEmpty
                ? _defaultImage(size)
                : _isLocalImage(avatarPath)
                    ? Image.file(
                        File(avatarPath),
                        width: size,
                        height: size,
                        fit: BoxFit.cover,
                      )
                    : Stack(
                        children: [
                          _defaultImage(size),
                          CircleAvatar(
                            radius: size / 2,
                            backgroundColor: Colors.transparent,
                            backgroundImage: avatarPath.startsWith('http')
                                ? NetworkImage(avatarPath)
                                : AssetImage(avatarPath) as ImageProvider,
                          )
                        ],
                      ))
            : Image.asset(R.unloginUserIcon),
      ),
    );
  }

  // 默认图标
  Widget _defaultImage(double size) {
    return Center(
      child: CircleAvatar(
        radius: size / 2,
        backgroundColor: LxCol.theme,
        child: Icon(
          Icons.person,
          color: Colors.white,
          size: 2 * size / 3,
        ),
      ),
    );
  }

  // 是否本地图片
  bool _isLocalImage(String path) {
    return path.startsWith('file://') || path.startsWith('/private/var');
  }
}
